let v = new Vue({
    el: '#app',
    data: {
            active:2,
            user:{
                id:-1
            },
            checkUser:{         //修改用户信息
                username:'',
                email:'',
                password:'',
                phone:''
            },
            password:{          //新密码
                oldPwd:'',
                newPwd:'',
                newPwd2:'',
                checkPwdMsg:' '
            },
            addresses:[],       //原有地址信息
            new_address:{       //新增地址信息
                name:'',
                phone:'',
                address:'',
                isDefault:'',
                region:''
            },
            user_arrival_order:[],      //用户待收货的订单
            pageInfo:{},     //用户收藏的商品
            user_evaluate_order:[]     //用户待评价订单
    },
    methods: {
        /** 用户个人中心功能开始 **/
        changeActive:function (i){
            this.active = i ;
        },
        findUserDetail:function (){
            axios.get(`user/findUserDetail/${this.user.id}`)
                .then(rsp=>{
                    if (rsp.data.flag){
                        this.user = rsp.data.data;
                        this.checkUser = JSON.parse(JSON.stringify(rsp.data.data));
                    }
                })
                .catch(e=>{
                    layer.msg(e.message);
                })
        },
        checkEmail:function (event){
            //如果数据没变动
            if (this.user.email === this.checkUser.email){
                return false;
            }
            let regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
            if (!regEmail.test(this.user.email)){
                layer.msg("邮箱格式不正确，请重新输入");
                $(event.target).addClass('input-error');
            }else{
                axios({
                    url:`checkEmail/${this.user.email}`
                }).then(response=>{
                    if (response.data.flag){
                        $(event.target).removeClass('input-error');
                    }else{
                        layer.msg(this.checkEmailMsg=response.data.data);
                        $(event.target).addClass('input-error');
                    }
                }).catch(error=>{
                    layer.msg(error.message);
                })
            }
        },
        checkUserName:function (event){
            //如果数据没变动
            if (this.user.username === this.checkUser.username){
                return false;
            }
            let regName = /(^[a-zA-Z0-9_-]{4,16}$)|(^[\u2E80-\u9FFF]{2,8})/;
            if (!regName.test(this.user.username)){
                layer.msg("用户名不规范，用户名可以是2-8位中文或者4-16位英文和数字的组合");
                $(event.target).addClass('input-error');
            }else{
                axios({
                    url:`checkUserName/${this.user.username}`
                }).then(response=>{
                    if (response.data.flag){
                        $(event.target).removeClass('input-error');
                    }else{
                        layer.msg(this.checkEmailMsg=response.data.data);
                        $(event.target).addClass('input-error');
                    }
                }).catch(error=>{
                    layer.msg(error.message);
                })
            }
        },
        checkPhone:function (event){
            //如果数据没变动
            if (this.user.phone === this.checkUser.phone){
                return false;
            }
            let regPhone = /^1[3|4|5|8][0-9]\d{8}$/;
            this.isFlag = regPhone.test(this.user.phone);
            if (!this.isFlag){
                layer.msg("手机格式不正确，请重新填写");
                $(event.target).addClass('input-error');
            }else{
                $(event.target).removeClass('input-error');
            }
        },
        //修改用户信息
        updateUser:function (){
            let flag = 1;
            // 表单中不能包含有input-error的输入框
            $("#user_from").find('input[class*="input-error"]').each(function () {
                flag = 0;
                return false;
            });
            if (flag){
                if (this.checkUser === this.user){
                    //数据没变动
                    return false;
                }else{
                    axios.put(`user/updateUser/${this.user.id}`,this.user)
                        .then(rsp=>{
                            if (rsp.data.flag){
                                layer.msg("保存成功");
                                //覆盖原有数据
                                $.cookie("userId", rsp.data.data.id, {path: "/", expires: 7});
                                 localStorage.setItem("username",rsp.data.data.username);
                                //重新查询用户
                                this.findUserDetail();
                            }
                        })
                        .catch(e=>{
                            layer.msg(e.message);
                        })
                }
            }else{
                layer.msg("信息填写有误，请重新检查一下");
            }
        },
        upload:function (e){
            let file = e.target.files[0];
            let param = new FormData(); //创建form对象
            param.append('file',file);//通过append向form对象添加数据
            console.log(param.get('file')); //FormData私有类对象，访问不到，可以通过get判断值是否传进去
            let config = {
                headers:{'Content-Type':'multipart/form-data'}
            }; //添加请求头
            axios.post(`user/upload/${this.user.id}`,param,config)
                .then(response=>{
                    if (response.data.flag){
                        layer.msg("上传成功");
                        this.findUserDetail();
                    }else{
                        layer.msg("上传失败");
                    }
                })
        },
        checkPassword:function (){
            if (this.password.newPwd === '' || this.password.newPwd!==this.password.newPwd2){
                this.password.checkPwdMsg = "两次输入的密码不正确，请重新输入";
            }else if(this.password.oldPwd === ''){
                this.password.checkPwdMsg = "旧密码不能为空，请重新输入";
            } else{
                this.password.checkPwdMsg="";
            }
        },
        updateUserPassword:function (){
            if (this.password.checkPwdMsg!==""){
                layer.msg("信息填写有误，请确认");
            }else {
                axios.put(`user/updateUserPassword/${this.user.id}`,this.password)
                    .then(rsp=>{
                        if (rsp.data.flag){
                            layer.msg("修改成功,3秒后跳转到登录页面");
                            //清空session和cookie的数据
                            $.removeCookie("userId",{path: "/"});
                             localStorage.removeItem("userId");
                             localStorage.removeItem("username");
                            setTimeout(()=>{
                                location.href='/toLogin' },3000)
                        }
                    })
                    .catch(e=>{
                    layer.msg(e.message);
                })
            }
        },
        /** 用户个人中心功能结束 **/
        /** 用户收货地址功能开始 **/
        findUserAddress:function (){
            axios(`address/findUserAll/${this.user.id}`)
                .then(rsp=>{
                    if (rsp.data.flag){
                        this.addresses = rsp.data.data;
                    }
                })
                .catch(e=>{
                    layer.msg(e.message);
                })
        },
        deleteAddress:function (id){
            layer.confirm('是否删除该地址', {
                btn: ['确认','取消'], //按钮
                yes:()=>{
                    axios({
                        url:`address/deleteAddress/${id}`
                    }).then(response=>{
                        if (response.data.flag){
                            layer.msg("删除成功");
                            this.findUserAddress();
                        }
                    }).catch(e=>{
                        layer.msg(e.message);
                    });
                }
            })
        },
        setDefaults:function (id){
            axios.put(`address/updateDefaults/${id}/${this.user.id}`)
                .then(response=>{
                    if (response.data.flag){
                        layer.msg("设置成功");
                        this.findUserAddress();
                        this.findUserDetail();
                    }
            }).catch(e=>{
                layer.msg(e.message);
            });
        },
        insertAddress:function () {
            //获取区域的值
            this.new_address.region = document.getElementById('Map_input_callback').value;
            if (this.new_address.region === '' || this.new_address.address === ''|| this.new_address.name === '' || this.new_address.phone === ''){
                layer.msg("信息填写不完整，请重新填写");
                return false;
            }else{
                //检查手机格式是否正确
                let regPhone = /^1[3|4|5|8][0-9]\d{8}$/;
                this.isFlag = regPhone.test(this.new_address.phone);
                if (!this.isFlag) {
                    layer.msg("手机格式不正确，请重新填写");
                    return false;
                }else{
                    //判断是否默认设置成默认地址
                    this.new_address.isDefault = this.new_address.isDefault === true?'1':'0';
                    axios.post(`address/insertAddress/${this.user.id}`,this.new_address)
                        .then(rsp=>{
                            if (rsp.data.flag){
                                layer.msg("添加成功");
                                this.new_address.isDefault = false;
                                this.new_address.name = '';
                                this.new_address.region = '';
                                this.new_address.phone = '';
                                this.new_address.address = '';
                                document.getElementById('Map_input_callback').value = "";
                                this.findUserDetail();
                                this.findUserAddress();
                            }
                        })
                        .catch(e=>{
                            layer.msg(e.message);
                        })
                }
            }
        },
        toUpdate:function (id){
            layer.aid = id;
            layer.uid = this.user.id;
            layer.open({
                type: 2,
                shadeClose: false,
                area: ['60%', '70%'],
                content: 'update_address.html', //iframe的url
                end:()=>{   //处理更新数据后响应结果
                    if (layer.message !== undefined && layer.message > 0){
                        layer.msg("修改成功");
                        layer.message = 0;
                        this.findUserDetail();
                        this.findUserAddress();
                    }
                }
            });
        },
        /** 用户收货地址功能结束 **/
        /** 用户订单功能开始 **/
        findArrivalOrder:function(){
            axios(`order/findArrivalOrder/${this.user.id}`)
                .then(rsp=>{
                    if (rsp.data.flag){
                        this.user_arrival_order = rsp.data.data;
                    }
                })
                .catch(error=>{
                    layer.msg(error.message);
                });
        },
        confirmReceipt:function (goods) {
            axios.put(`order/confirmReceipt`,goods)
                .then(rsp=>{
                    if (rsp.data.flag){
                        layer.msg("确认收货成功");
                        this.findArrivalOrder();
                        this.findEvaluateOrder();
                    }
                })
                .catch(error=>{
                    layer.msg(error.message);
                });
        },
        /** 用户订单功能结束 **/
        /** 用户评价功能开始 **/
        findEvaluateOrder:function () {
            axios(`order/findEvaluateOrder/${this.user.id}`)
                .then(rsp=>{
                    if (rsp.data.flag){
                        this.user_evaluate_order = rsp.data.data;
                    }
                })
                .catch(error=>{
                    layer.msg(error.message);
                });
        },
        evaluate:function (goods) {
            axios.put(`order/evaluate`,goods)
                .then(rsp=>{
                    if (rsp.data.flag){
                        layer.msg("评价成功");
                        this.findUserDetail();
                        this.findEvaluateOrder();
                    }
                })
                .catch(error=>{
                    layer.msg(error.message);
                });
        },
        /** 用户评价功能结束 **/
        toGoodsDetail:function (id) {
             localStorage.setItem("aid",id);
        },
        findCollect:function (pageNum,pageSize) {
            axios(`user/findCollect/${pageNum}/${pageSize}`)
                .then(rsp=>{
                    if (rsp.data.flag){
                        this.pageInfo = rsp.data.data;
                    }
                })
                .catch(error=>{
                    layer.msg(error.message);
                });
        }
    },
    created: function () {
        this.user.id =  localStorage.getItem("userId");
        this.findCollect(1,15);
        this.findUserDetail();
        this.findUserAddress();
        this.findArrivalOrder();
        this.findEvaluateOrder();
    }
});